package com.uu.safeguard.utils;


import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

import static org.apache.commons.codec.digest.DigestUtils.sha1Hex;


public class WechatUtil {

    private String appid;
    private String secret;

    //获取用户信息
    public static JSONObject getUserInfo(String code, String appid, String secret){
        JSONObject useinfoJsonObject = new JSONObject();
        //获取access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
        String res = HttpUtil.get(url, new HashMap<>());
        JSONObject jsonObject = JSONObject.parseObject(res);
        if (!jsonObject.containsKey("access_token")) {
            return useinfoJsonObject;
        }
        String access_token = jsonObject.getString("access_token");
        String wechat_openid = jsonObject.getString("openid");

        //获取用户信息
        String useinfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + wechat_openid + "&lang=zh_CN";
        String useinfoRes = HttpUtil.get(useinfoUrl, new HashMap<>());
        useinfoJsonObject = JSONObject.parseObject(useinfoRes);

        return useinfoJsonObject;
    }


    /*
     * 获取access_token
     *  https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
     */
    public static String getAccessToken(String appid, String secret){
        int create_time = (int) (System.currentTimeMillis() / 1000);
        //判断缓存是否存在
        Jedis jedis = JedisUtil.getJedis();
        jedis.select(2);
        //查询缓存中是否存在
        String redisKey = "access_token_" + appid;
        if(jedis.exists(redisKey)){
            String access_token_str = jedis.get(redisKey);
            JSONObject jsonObject = JSONObject.parseObject(access_token_str);
            if((int) jsonObject.get("expire_time") > create_time){
                JedisUtil.close(jedis);
                return jsonObject.get("access_token").toString();
            }
        }
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        String res = HttpUtil.get(url, new HashMap<>());
        JSONObject jsonObject = JSONObject.parseObject(res);
        if (!jsonObject.containsKey("access_token")) {
            JedisUtil.close(jedis);
            return "";
        }
        jsonObject.put("expire_time", (int)jsonObject.get("expires_in") + create_time);
        jedis.set(redisKey,jsonObject.toString());
        jedis.expire(redisKey, (int)jsonObject.get("expires_in") - 60);
        JedisUtil.close(jedis);
        return jsonObject.get("access_token").toString();
    }

    /*
     * 获取jsapi_ticket
     *  https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
     */
    public static String getJsapiTicket(String access_token, String appid){
        int create_time = (int) (System.currentTimeMillis() / 1000);
        //判断缓存是否存在
        Jedis jedis = JedisUtil.getJedis();
        jedis.select(2);
        //查询缓存中是否存在
        String redisKey = "jsapi_ticket_" + appid;
        if(jedis.exists(redisKey)){
            String jsapi_ticket_str = jedis.get(redisKey);
            JSONObject jsonObject = JSONObject.parseObject(jsapi_ticket_str);
            if((int) jsonObject.get("expire_time") > create_time){
                JedisUtil.close(jedis);
                return jsonObject.get("ticket").toString();
            }
        }
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
        String res = HttpUtil.get(url, new HashMap<>());
        JSONObject jsonObject = JSONObject.parseObject(res);
        if (!jsonObject.containsKey("ticket")) {
            JedisUtil.close(jedis);
            return "";
        }
        jsonObject.put("expire_time", (int)jsonObject.get("expires_in") + create_time);
        jedis.set(redisKey,jsonObject.toString());
        jedis.expire(redisKey, (int)jsonObject.get("expires_in") - 60);
        JedisUtil.close(jedis);
        return jsonObject.get("ticket").toString();
    }

    /*
     * 获取jsdk签名数据
     */
    public static Map getJsSdkSignPackage(String appid, String secret, String url){
        String accessToken = getAccessToken(appid, secret);
        String jsapiTicket = getJsapiTicket(accessToken, appid);
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        String nonceStr = UUID.randomUUID().toString();
        String url1 = url;
        try {
            url1 = URLDecoder.decode(url,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        String string = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url1;

        String signature = sha1Hex(string);

        HashMap signPackage = new HashMap();
        signPackage.put("appId", appid);
        signPackage.put("nonceStr", nonceStr);
        signPackage.put("timestamp", timestamp);

        signPackage.put("url", url1);
        signPackage.put("signature", signature);
        signPackage.put("rawString", string);

        return signPackage;
    }

    //获取用户信息  https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
    public static JSONObject getUserInfoByOpenid(String appid, String secret, String wechat_openid){
        JSONObject useinfoJsonObject = new JSONObject();

        String access_token = getAccessToken(appid, secret);
        //获取用户信息
        String useinfoUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid=" + wechat_openid + "&lang=zh_CN";
        String useinfoRes = HttpUtil.get(useinfoUrl, new HashMap<>());
        useinfoJsonObject = JSONObject.parseObject(useinfoRes);

        return useinfoJsonObject;
    }

    //模板消息
/*    public static Map<String, String> sendTmplMsg(String appid, String secret, LinkedHashMap contentMap){

        String content = net.sf.json.JSONObject.fromObject(contentMap).toString();
        String access_token = getAccessToken(appid, secret);
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token ;
        String result = HttpUtil.post(url, new HashMap<>(), content);
        Map resultMap = JSONObject.parseObject(result);
        return resultMap;
    }*/
}
